package com.supermap.wzhy.module.user.api;

import com.supermap.wzhy.common.annotation.Permission;
import com.supermap.wzhy.common.annotation.Role;
import com.supermap.wzhy.common.api.BaseController;
import com.supermap.wzhy.data.OpStatus;
import com.supermap.wzhy.data.PageInfo;
import com.supermap.wzhy.entity.TUserpower;
import com.supermap.wzhy.entity.TUserpowercatalog;
import com.supermap.wzhy.entity.TUserrole;
import com.supermap.wzhy.entity.TUsers;
import com.supermap.wzhy.module.user.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by W.Hao on 14-2-27.
 * 用户权限
 */
@Controller
@RequestMapping(value = {"/powers","/service/powers"}, produces = "application/json")
public class PowerController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    PowerService powerService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    UserService userService;
    @Autowired
    PowerCatalogsService powerCatalogsService;
    @Autowired
    UserRolePowerService userRolePowerService ;

    @RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @Permission(Role.ADMIN)
    public OpStatus create(@RequestBody TUserpower entity) {

        if (entity.getTUserpowercatalog() != null) {
            TUserpower userpower = null;
            try {
                userpower = powerService.create(entity);
            } catch (Exception ex) {
                return getOpStatus(false);
            }
            if (userpower != null)
                return getOpStatus(true);
            else {
                return getOpStatus(false);
            }
        } else return getOpStatus(false);

    }

    @RequestMapping(value = "/{powerid}", method = RequestMethod.PUT)
    @ResponseBody
    @Permission(Role.ADMIN)
    public OpStatus update(@PathVariable("powerid") int powerid,@RequestBody TUserpower userpower) {
        if (powerService.update(powerid, userpower)) {
            return getOpStatus(true);
        } else
            return getOpStatus(false);
    }

    /**
     * 移动节点到指定权限分类的指定权限节点下
     *
     * @param pcataid
     *             移动到的权限分类id
     * @param parid
     *             移动到的父节点id
     * @return
     */
    @RequestMapping(value = "/{powerid}/moveItem", method = RequestMethod.PUT)
    @ResponseBody
    @Permission(Role.ADMIN)
    public OpStatus moveItem(@PathVariable("powerid") int powerid,int pcataid,int parid) {
        TUserpower userpower = powerService.getOne(powerid);
        if(userpower == null)
            return getOpStatus(false);
        userpower.setParid(parid);                          //设置新的parid
        TUserpowercatalog tUserpowercatalog = new TUserpowercatalog();
        tUserpowercatalog.setPcataid(pcataid);
        userpower.setTUserpowercatalog(tUserpowercatalog);  //设置新的权限分类

        if (powerService.update(powerid, userpower)) {
            return getOpStatus(true);
        } else
            return getOpStatus(false);
    }

    @Transactional
    @RequestMapping(value = "/{powerid}", method = RequestMethod.DELETE)
    @ResponseBody
    @Permission(Role.ADMIN)
    public OpStatus delete(@PathVariable("powerid") int powerid) {
        if (powerService.delete(powerid)) {
            return getOpStatus(true);
        } else
            return getOpStatus(false);
    }

    /**
     * 删除指定节点和其所有字节点的权限
     *
     * @param powerid
     *          指定节点的id
     * @return
     */
    @Transactional
    @RequestMapping(value = "/{powerid}/allChildrenItems", method = RequestMethod.DELETE)
    @ResponseBody
    @Permission(Role.ADMIN)
    public OpStatus deletePowerAndallChildrenItems(@PathVariable("powerid") int powerid){
        boolean re = false;

        TUserpower tUserpower = powerService.getOne(powerid);
        if(tUserpower != null){
            List<TUserpower> allChildren = powerService.getAllChildrenPoweridBypowerid(tUserpower.getTUserpowercatalog().getPcataid(),powerid);
            if(allChildren != null && allChildren.size() > 0){
                for (TUserpower child : allChildren){
                    re = powerService.delete(child.getPowerid());
                }
            }
            re = powerService.delete(powerid);  //删除自己
        }
        return getOpStatus(re);
    }


    /**
     * 删除指定节点和其所有字节点的权限
     *
     * 说明：（此操作会删除该节点及其所有子节点）
     * 按照ID删除（不（强制）关联删除）
     * 删除的时候若该权限及其所有子权限都不被用户或者角色使用，才可以删除
     *
     * @param powerid
     *          指定节点的id
     * @return
     */
    @Transactional
    @RequestMapping(value = "/{powerid}/allChildrenItems/noforedelete", method = RequestMethod.DELETE)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Map<String,Object> deletePowerAndallChildrenItemsForNoForce(@PathVariable("powerid") int powerid){
        return powerService.deletePowerAndallChildrenItemsForNoForce(powerid);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Page<TUserpower> getAll(PageInfo pageInfo) {
        return powerService.findAll(getPageRequest(pageInfo));
    }

    @RequestMapping(value = "/{powerid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @Permission(Role.ADMIN)
    public TUserpower getPower(@PathVariable("powerid") int powerid) {
        log.debug("powerid get");
        TUserpower query = new TUserpower();
        query.setPowerid(powerid);
        TUserpower re = powerService.one(query);
        //System.out.println(re.getTUserpowercatalog().getName());
        return re;
    }

    /**
     * 获取指定父节点下的一级子节点
     *
     * @param powerid
     *            父节点
     * @param pcataid
     *            指定权限分类
     * @return
     */
    @Transactional
    @RequestMapping(value = "/{powerid}/nextSub", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Map<String,Object> getPowerListBypcataidAndparid(@PathVariable("powerid") int powerid,int pcataid) {

        Map<String,Object> re = new HashMap<>();

        List<TUserpower> list = powerService.getPowerBypcataIdAndParid(pcataid,powerid);

        //没有子节点,并且父节点不是跟节点，读取自己的值
        if(list != null && list.size() == 0 && powerid != 0){
            TUserpower tUserpower = powerService.getOne(powerid);
            if(tUserpower != null)
                list.add(tUserpower);
        }

        re.put("content",list);
        return re;
    }


    /**
     * 按照power找Users
     *
     * @param powerid
     * @return
     */
    @RequestMapping(value = "/{powerid}/users", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public List<TUsers> getUsersByPower(@PathVariable("powerid") Integer powerid) {
        return userService.findUsersByPower(powerid);
    }

    /**
     * 按照power找Roles
     *
     * @param powerid
     * @return
     */
    @Transactional
    @RequestMapping(value = "/{powerid}/roles", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public List<TUserrole> getUserrolesByPower(@PathVariable("powerid") Integer powerid) {
        List<TUserrole> userroleList = userRoleService.findUserrolesByPower(powerid);
        return userroleList;
    }


    /**
     * 获取权限分类树型结构
     *
     *
     * @return
     */
    @RequestMapping(value = "/powerCatalogTree", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Map<String,Object> getRootPowerTree(){
        return powerService.getRootPowers();
    }

    /**
     * 获取权限分类的树型结构下的第一级数据
     *
     * @return
     */
    @RequestMapping(value = "/powerCatalogTree/{pcataid}", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Map<String,Object> getRootPowerTreeLeafByPcataid(@PathVariable("pcataid") int pcataid){
        return powerService.getRootPowerTreeLeafByPcataid(pcataid);
    }

    /**
     * 获取指定权限下powerid的子节点
     *
     * @return
     */
    @RequestMapping(value = "/powerTree/{powerid}", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Map<String,Object> getPowerTreeLeafBypowerid(@PathVariable("powerid") int powerid){
        return powerService.getPowerTreeLeafBypowerid(powerid);
    }

    /**
     * 获取权限树 系统+数据
     * @return
     */
    @RequestMapping(value = "/{userid}/tree", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public Map<String,Object> getPowerTree(@PathVariable("userid")int userid,
                                          HttpServletRequest request) {
        TUsers currUser = getSessionUser(request) ;
        if(null == currUser){
            return  null ;
        }
//        int userid = currUser.getUserid() ;
        return userRolePowerService.getAllPowers(userid);
    }

    /**
     * 获取某个节点下的权限
     * @param userid 或者 roleid
     * @param selId
     * @param type
     * @return
     */
    @RequestMapping(value = "/{userid}/tree/{selId}", method = RequestMethod.GET)
    @ResponseBody
    @Permission(Role.ADMIN)
    public List getPowerInfos(@PathVariable("userid") int userid,@PathVariable("selId") String selId,String type
                              ) {
        return userRolePowerService.getPowerListByType(userid,selId,type);
    }


    /**
     * 设置权限
     * @param userid or roleid
     * @param selId
     * @param type u or r
     * @param dataids
     * @return
     */
    @RequestMapping(value = "/{userid}/tree/{selId}/setpowers", method = RequestMethod.POST)
    @ResponseBody
    @Permission(Role.ADMIN)
    public OpStatus setPowers(@PathVariable("userid") int userid,@PathVariable("selId") String selId,
                            String type,@RequestBody int[] dataids ) {
        boolean re = userRolePowerService.setPowers(userid,selId,dataids,type);
        return getOpStatus(re);
    }
}
